#!/bin/sh

# id of the user running qemu (kvm). Make sure you change it appropriately.
USERID=1000

# number of TUN/TAP devices to setup
NUM_OF_DEVICES=2

IPADDR=193.168.20.133
GATEWAY=193.168.20.2

case $1 in
	stop)
		echo "STOP QEMU ..."
		for ((i=0; i < NUM_OF_DEVICES ; i++)); do
			ifconfig tap$i down
			brctl delif br0 tap$i
			tunctl -d tap$i
		done
		brctl delif br0 eth0
		ifconfig br0 down
		brctl delbr br0
		/etc/init.d/vtun stop
		ifconfig eth0 $IPADDR netmask 255.255.255.0 up
		ip route add via $GATEWAY dev eth0
		tunctl -d tap8
		rmmod kvm_intel
		rmmod kvm
		;;

	*)
		echo "START QEMU ..."
		ifconfig eth0 0
		ifconfig wlan0 down
		modprobe tun
		/etc/init.d/vtun start
		chmod a+rw /dev/net/tun
		echo -n "Setting up bridge device br0"
		brctl addbr br0
		ifconfig br0 $IPADDR netmask 255.255.255.0 up
		for ((i=0; i < NUM_OF_DEVICES ; i++)); do
			echo -n "Setting up "
			tunctl -b -u $USERID -t tap$i
			brctl addif br0 tap$i
			ifconfig tap$i up 0.0.0.0 promisc
		done
		brctl addif br0 eth0
		ip route add via $GATEWAY dev br0
		modprobe kvm_intel
		tunctl -b -u $USERID -t tap8
		tunctl -b -u $USERID -t tap9
		ifconfig tap8 up
		ifconfig tap9 up
		ifconfig tap8 promisc
		ifconfig tap9 promisc
		brctl addbr br1
		brctl addif br1 tap8
		brctl addif br1 tap9
		ifconfig br1 192.168.56.1 netmask 255.255.255.0
		;;
esac

